<template>
  <div>
    <van-nav-bar title="登入" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="loginname"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号校验失败' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,16}$/, message: '密码需要6-16位数' }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'

import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      loginname: '17704051019',
      password: '123456'
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    onClickLeft () {
      this.$router.push('/')
    },
    async onSubmit () {
      try {
        const res = await login({
          loginname: this.loginname,
          password: this.password
        })
        Toast({
          duration: 800,
          type: 'success',
          message: res.message,
          onClose: () => {
            // 跳转到layout
            this.setToken(res.data.token)
            if (this.$route.query.redirect) {
              this.$router.push(this.$route.query.redirect)
            } else {
              this.$router.push('/')
            }
          }
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped>
::v-deep(.van-nav-bar .van-icon) {
  color: #000;
}
::v-deep(.van-button--info) {
  color: #fff;
  background-color: #c82519;
  border: 1px solid #c82519;
}
</style>
